package com.itxialu.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itxialu.reggie.common.R;
import com.itxialu.reggie.entity.Category;
import com.itxialu.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 *
 * @author shkstart
 * @create 2022-10-02 19:57
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody Category category) {
        log.info("新增分类：{}", category);
        categoryService.save(category);
        return R.success("新增分类成功！");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        //创建分页构造器
        Page<Category> pageInfo = new Page<>();
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        //LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //过滤条件
        //排序
        wrapper.orderByAsc("sort");
        //wrapper.orderByAsc(Category::getSort);
        categoryService.page(pageInfo, wrapper);
        return R.success(pageInfo);
    }

    //根据ID删除分类
    @DeleteMapping
    public R<String> delete(long ids) {
        log.info("删除分类，ID为：{}", ids);
        //categoryService.removeById(ids);
        categoryService.remove(ids);
        return R.success("分类信息删除成功！");
    }

    //根据ID修改菜品分类
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        log.info("修改分类信息");
        categoryService.updateById(category);
        return R.success("修改分类信息成功");
    }

    //根据条件查询分类数据，下拉框查询
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        //条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //添加条件(条件，具体的条件，值)
        wrapper.eq(category.getType() != null, Category::getType, category.getType());
        //添加排序条件Asc:升序,Desc:降序
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }

}
